
import React from "react";
import * as THREE from 'three';
import { useAnimate } from "tools/hooks/useAnimate";
import Controller from "../Controller";
import { GLTF } from "../Controller/State/Element";

/** 创建渲染器   */
export default function useRenderer(controller: Controller) {

    /** canvas 容器 */
    const cont = controller.useMemo(s => s.cont, []);

    /** 渲染器 */
    const renderer = controller.useMemo(s => s.renderer, []);

    /** 场景 */
    const scene = controller.useMemo(s => s.scene, []);

    /** 原件字典 */
    const elementMap = controller.useMemo(s => s.elementMap, []);

    /** 摄像机 */
    const camera = controller.useMemo(s => s.camera, []);

    React.useEffect(() => {
        if (!cont) return;
        controller.run(async s => {
            cont.innerHTML = "";
            s.renderer = new THREE.WebGLRenderer({ antialias: true });
            s.renderer.setClearColor(new THREE.Color(0xffffff));
            s.renderer.setSize(cont.offsetWidth, cont.offsetHeight);
            s.renderer.shadowMap.enabled = true;
            s.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
            cont.appendChild(s.renderer.domElement);
        })
    }, [cont, controller])

    useAnimate(React.useCallback(() => {
        // 基础渲染
        if (renderer && scene && camera) {
            renderer.render(scene, camera);
        };

        // 渲染动画
        elementMap.forEach(e => {
            if (e.object3D instanceof GLTF) {
                if (e.object3D.mixer) e.object3D.mixer.update(e.object3D.clock.getDelta());
            }
        })
    }, [camera, renderer, scene, elementMap]))
}